<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <!--添加角色区域-->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addDialogVisible = true">添加角色</el-button>
        </el-col>
      </el-row>
      <!--  角色列表表格区域-->
      <el-table :data="roleslist" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row v-for="(item, i) in scope.row.children" :key="item.id" :class="['bd-bottom', i === 0 ? 'bd-top' : '', 'vcenter']">
              <!-- 一级权限 -->
              <el-col :span="6">
                <el-tag closable @close="removeRightById(scope.row, item.id)">{{ item.authName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="18">
                <el-row v-for="(subItem, s) in item.children" :key="subItem.id" :class="[s === 0 ? '' : 'bd-top', 'vcenter']">
                  <!-- 二级权限 -->
                  <el-col :span="6">
                    <el-tag closable type="success" @close="removeRightById(scope.row, subItem.id)">{{ subItem.authName }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18">
                    <el-tag closable type="warning" v-for="valid in subItem.children" :key="valid.id" @close="removeRightById(scope.row, valid.id)">{{ valid.authName }}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>

        <!-- 索引列 -->
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <!-- 操作 -->
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 编辑 -->
            <el-tooltip class="item" effect="dark" content="编辑" placement="top">
              <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditDialog(scope.row.id)">编辑</el-button>
            </el-tooltip>
            <!-- 删除 -->
            <el-tooltip class="item" effect="dark" content="删除" placement="top">
              <el-button type="warning" size="mini" icon="el-icon-delete" @click="removeEditDialog(scope.row.id)">删除</el-button>
            </el-tooltip>
            <!-- 分配角色 -->
            <el-tooltip class="item" effect="dark" content="分配角色" placement="top">
              @click="setRightsDialog(scope.row)"
              <el-button type="danger" size="mini" icon="el-icon-setting" @click="setRightsDialog(scope.row)">分配角色</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色 对话框 -->
    <el-dialog title="添加角色" :visible.sync="addDialogVisible" @close="addRolesClose" width="34%">
      <el-form :model="rolesForm" :rules="rolesFormRules" ref="rolesFormRef" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="rolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="rolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑角色 对话框 -->
    <el-dialog title="编辑角色" :visible.sync="editDialogVisible" width="34%">
      <el-form :model="editRolesForm" :rules="rolesFormRules" ref="editRolesFormRef" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoles">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog title="分配权限" :visible.sync="assignVisible" width="34%" @close="setRightsDialogClosed">
      <!-- tree树形控件 -->
      <el-tree :data="rightslist" show-checkbox default-expand-all node-key="id" ref="treeRef" :props="treeProps" :default-checked-keys="defKeys"> </el-tree>

      <span slot="footer" class="dialog-footer">
        <el-button @click="assignVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Roles',
  data() {
    return {
      // 角色列表数据
      roleslist: [],
      // 对话框显示与隐藏
      addDialogVisible: false,
      editDialogVisible: false,
      assignVisible: false,
      // 添加角色的表单数据
      rolesForm: {
        roleName: '',
        roleDesc: ''
      },
      // 表单的验证规则对象
      rolesFormRules: {
        roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
        roleDesc: [{ required: true, message: '请输入角色描述', trigger: 'blur' }]
      },
      // 编辑角色的表单数据对象
      editRolesForm: {
        roleName: '',
        roleDesc: ''
      },
      // 角色唯一的id值
      rolesID: 0,
      // 所有分配权限数据列表
      rightslist: [],
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 默认选中的节点id值
      defKeys: [],
      treeID: ''
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    // 获取角色列表参数
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      this.roleslist = res.data
      console.log(res)
    },
    // 添加角色 请求
    addRoles() {
      this.$refs.rolesFormRef.validate(async valid => {
        if (!valid) return this.$message.info('请先填选项值')
        const { data: res } = await this.$http.post('roles', this.rolesForm)
        if (res.meta.status !== 201) return this.$message.error('添加角色失败')
        this.getRolesList()
        this.addDialogVisible = false
        this.$message.success('添加角色成功')
      })
    },
    // 监听添加角色的关闭事件
    addRolesClose() {
      this.$refs.rolesFormRef.resetFields()
    },
    // 点击编辑按钮  查询id参数 并弹出对话框
    async showEditDialog(id) {
      this.rolesID = id
      const { data: res } = await this.$http.get(`roles/${id}`)
      if (res.meta.status !== 200) return this.$message.error('查询id失败')
      this.editRolesForm = res.data
      this.editDialogVisible = true
    },
    // 修改角色
    editRoles() {
      this.$refs.editRolesFormRef.validate(async valid => {
        if (!valid) return this.$message.error('请完善选项值!')
        const { data: res } = await this.$http.put(`roles/${this.rolesID}`, this.editRolesForm)
        if (res.meta.status !== 200) return this.$message.error('修改角色失败')
        this.getRolesList()
        this.editDialogVisible = false
        this.$message.success('修改角色成功')
      })
    },
    // 删除角色
    async removeEditDialog(id) {
      const configfirm = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (configfirm !== 'confirm') {
        return this.$message.info('已取消删除')
      } else {
        const { data: res } = await this.$http.delete(`roles/${id}`)
        if (res.meta.status !== 200) return this.$message.error('删除角色失败')
        this.getRolesList()
        this.$message.success('删除角色成功')
      }
    },
    // 展示分配角色权限 对话框
    async setRightsDialog(roles) {
      this.treeID = roles.id
      // 获取所有权限的数据
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限数据失败')
      }
      this.rightslist = res.data
      this.getLeafKeys(roles, this.defKeys)
      this.assignVisible = true
    },
    // 通过递归形式获取
    getLeafKeys(nodes, arr) {
      if (!nodes.children) {
        return arr.push(nodes.id)
      }
      nodes.children.forEach(item => this.getLeafKeys(item, arr))
    },
    //  点击为角色分配权限
    async allotRights() {
      const keys = [...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()]
      console.log(keys)
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.treeID}/rights`, { rids: idStr })
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败')
      } else {
        this.getRolesList()
        this.assignVisible = false
        this.$message.success('分配权限成功')
      }
    },
    // 监听分配权限关闭事件 重置id值
    setRightsDialogClosed() {
      this.defKeys = []
    },
    // 根据id权限删除对应的权限
    async removeRightById(colres, closeID) {
      const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除权限')
      }
      const { data: res } = await this.$http.delete(`roles/${colres.id}/rights/${closeID}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除权限失败')
      } else {
        colres.children = res.data
        this.$message.success('删除权限成功')
      }
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bd-top {
  border-top: 1px solid #eee;
}

.bd-bottom {
  border-bottom: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>
